<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isUpdate ? '修改评论' : '添加评论'"
    width="500px"
    :before-close="handleClose"
  >
    <div class="comment-form">
      <!-- 评分 -->
      <div class="form-item">
        <label>评分</label>
        <el-rate v-model="commentForm.rating" :max="5" />
      </div>

      <!-- 评论内容 -->
      <div class="form-item">
        <label>评论内容</label>
        <el-input
          v-model="commentForm.content"
          type="textarea"
          :rows="4"
          placeholder="请输入您的评论内容"
        />
      </div>

      <!-- 图片上传 -->
      <div class="form-item">
        <label>上传图片（选填）</label>
        <el-upload
          v-model:file-list="fileList"
          :http-request="customUpload"
          list-type="picture-card"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          accept="image/*"
          :limit="5"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png/gif文件，且不超过2MB
            </div>
          </template>
        </el-upload>
      </div>

      <!-- 匿名评论 -->
      <div class="form-item">
        <el-checkbox v-model="commentForm.isAnonymous">匿名评论</el-checkbox>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isUpdate ? '修改' : '提交' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onBeforeUnmount, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { uploadCommentImage } from '../axios/comment'

const props = defineProps({
  orderId: {
    type: Number,
    required: true,
    default: 0
  },
  visible: {
    type: Boolean,
    required: true
  },
  isUpdate: {
    type: Boolean,
    default: false
  },
  comment: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'submit'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const fileList = ref([])
const submitting = ref(false)

const commentForm = reactive({
  orderId: props.orderId,
  content: '',
  rating: 5,
  images: '',
  isAnonymous: false
})

// 监听 props.orderId 和 props.isUpdate 的变化
watch([() => props.orderId, () => props.isUpdate], ([newOrderId, newIsUpdate]) => {
  if (newOrderId) {
    commentForm.orderId = newOrderId
    if (newIsUpdate && props.comment) {
      // 直接使用传入的评论数据
      commentForm.content = props.comment.content
      commentForm.rating = props.comment.rating
      commentForm.images = props.comment.images
      commentForm.isAnonymous = props.comment.isAnonymous === 1
      
      // 如果有图片，添加到文件列表
      if (props.comment.images) {
        const imageUrls = props.comment.images.split(',')
        fileList.value = imageUrls.map(url => ({
          name: url.split('/').pop(),
          url: url
        }))
      }
    } else {
      // 重置表单
      resetForm()
    }
  }
}, { immediate: true })

// 监听对话框可见性变化
watch(() => props.visible, (newVal) => {
  if (newVal && props.isUpdate && props.orderId) {
    // 获取已有评论
    // fetchExistingComment()
  }
})

// 重置表单
const resetForm = () => {
  commentForm.content = ''
  commentForm.rating = 5
  commentForm.images = ''
  commentForm.isAnonymous = false
  fileList.value = []
}

// 自定义上传方法
const customUpload = async ({ file }) => {
  try {
    const response = await uploadCommentImage(file)
    if (response.code === 1 && response.data) {
      const imageUrl = response.data
      const currentImages = commentForm.images ? commentForm.images.split(',') : []
      currentImages.push(imageUrl)
      commentForm.images = currentImages.join(',')
      
      ElMessage.success('图片上传成功')
      return response.data // 返回图片URL，让el-upload组件处理文件列表
    } else {
      ElMessage.error(response.msg || '图片上传失败')
      return false
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
    return false
  }
}

// 处理移除图片
const handleRemove = (file) => {
  const imageUrl = file.url || file.response
  if (imageUrl) {
    const images = commentForm.images ? commentForm.images.split(',') : []
    const index = images.indexOf(imageUrl)
    if (index > -1) {
      images.splice(index, 1)
      commentForm.images = images.length ? images.join(',') : ''
    }
  }
}

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交评论
const handleSubmit = async () => {
  if (!commentForm.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  if (commentForm.rating === 0) {
    ElMessage.warning('请选择评分')
    return
  }

  if (!commentForm.orderId) {
    ElMessage.error('订单信息不完整')
    return
  }

  submitting.value = true
  try {
    // 确保发送的数据格式正确
    const submitData = {
      orderId: commentForm.orderId,
      content: commentForm.content.trim(),
      rating: commentForm.rating,
      images: commentForm.images || '',
      isAnonymous: commentForm.isAnonymous ? 1 : 0
    }
    emit('submit', submitData)
    handleClose()
  } catch (error) {
    console.error('提交评论失败:', error)
    ElMessage.error('提交评论失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 组件卸载前清理
onBeforeUnmount(() => {
  handleClose()
})

// 组件挂载时，如果是修改评论，则获取已有评论
onMounted(() => {
  if (props.isUpdate) {
    // 获取已有评论
    // fetchExistingComment()
  }
})
</script>

<style scoped>
.comment-form {
  padding: 20px 0;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 